package com.mmall.concurrency.unsafeClass;

import com.mmall.concurrency.annotations.NotThreadSafe;
import com.mmall.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@ThreadSafe
public class StringBufferDemo {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    public static StringBuffer stringBuffer = new StringBuffer();

    public static void main(String[] args) throws Exception{
        // 定义线程池和信号量
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i++){
            executorService.execute( () -> {
                // 线程里执行，加解锁，中间执行
                try {
                    semaphore.acquire();
                    appendL();
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 :{}", e);
                }
                countDownLatch.countDown();
            } );
        } // for
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}", stringBuffer.length());

    }

    public static void appendL(){
        stringBuffer.append("h");
    }
}
